package com.wanmait.teatrain.interceptor;
import com.wanmait.teatrain.entity.Admin;
import com.wanmait.teatrain.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTinterceptor implements HandlerInterceptor {
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Value("${token.secret}")
    private String secret;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 预检请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("token");
        //判断token是否为空
        if (token == null || token.trim().isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            //验证密钥是否正确
            JWTUtils.verifyToken(token, secret);
            // 从Redis获取用户信息
            Admin admin = (Admin) redisTemplate.opsForValue().get("token:" + token);
            if (admin == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            // 存入请求域，后续业务使用
            request.setAttribute("loginEmp", admin);
            return true;
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
}
